from settings import testdates_path
from tools.global_data import GlobalData
from tools.handle_assert_db import check_db
from tools.handle_assert_response import check_response
from tools.handle_pre_sql import excute_pre_sql
from tools.handle_replace_mark_data import replace_mark_data_by_re
from tools.handle_requests import HandleRequests
from tools.handle_response import transfer_response_to_dict
from tools.handle_response_extract import extract_data_from_response
from tools.my_excel import MyExcel
from loguru import logger
import allure

class BaseCase:

    def base_case(self, case, hreq):
        logger.info(f'===测试用例{case["title"]}===')
        # 2.excel中有pre_sql字段，则先执行前置sql语句
        if case.get("pre_sql"):
            excute_pre_sql(case["pre_sql"])

        # 3.处理请求数据,替换占位符
        if case.get("req_data"):
            case["req_data"] = replace_mark_data_by_re(case["req_data"])

        # 4.发送请求
        # 全局变量有token，则传token
        if hasattr(GlobalData, "token") and ("ogin" not in case["url"]):
            resp = hreq.send_requests(case["method"], case["url"],
                                           json=case["req_data"], files=case["files"],
                                           token=getattr(GlobalData, "token"))
        # 全局变量无token，则不传
        else:
            resp = hreq.send_requests(case["method"], case["url"],
                                           json=case["req_data"], files=case["files"])

        # 5.将响应结果转为dict
        resp_dict = transfer_response_to_dict(resp)

        # 6.将响应结果的值通过jsonpath设置为全局变量，供下一个接口使用
        if case.get("extract"):
            extract_data_from_response(resp_dict, (case["extract"]))

        # 7.响应结果断言
        if case.get("check_response"):
            check_response(resp_dict, case["check_response"])

        # 8.数据库断言
        if case.get("check_db"):
            check_db(case.get("check_db"))
